import time
from sqlmodel import Session, select, insert, delete
from typing import Optional, List

from app.exception.base import AppException, HttpResp
from app.models.system_menu import SystemMenu
from app.models.system_role_menu import SystemRoleMenu
from app.models.system_role import SystemRole
from app.utils.array import ArrayUtil


class SystemRoleMenuService:
    """系统权限服务实现类"""

    def __init__(self, session: Session):
        self.session = session

    async def select_menu_ids_by_role_id(self, role_ids: List[int]) -> List[int]:
        """根据角色ID获取菜单ID"""
        statement = select(SystemRole).where([SystemRole.id.in_(role_ids), SystemRole.is_disable == 0])
        role = self.session.exec(statement).one()
        # 如果一个角色都没查到，则判断没有角色
        if not role:
            return []
        perms = self.session.exec(
            select(SystemRoleMenu).where(SystemRoleMenu.role_id.in_(role_ids))
        ).all()
        menu_ids = {i.menu_id for i in perms}  # 使用 set 去重
        return list(menu_ids)  # 转换回 list
        # return [i.menu_id for i in perms]

    async def cache_role_menus_by_role_id(self, role_id: int):
        """缓存角色菜单"""
        statement = select(SystemRoleMenu).where(SystemRoleMenu.role_id == role_id)
        auth_perms = self.session.exec(statement).all()
        menu_ids = [i.menu_id for i in auth_perms]
        menus = []
        if menu_ids:
            auth_menus = self.session.exec(
                select(SystemMenu).where([
                    SystemMenu.id.in_(menu_ids),
                    SystemMenu.is_disable == 0,
                    SystemMenu.menu_type.in_(['C', 'A']),
                ]).order_by(SystemMenu.menu_sort, SystemMenu.id)
            )
            menus = [i.perms for i in auth_menus if i.perms]
        # 将 menus 缓存入Redis
        return menus

    async def batch_delete_by_role_id(self, role_id: int):
        """批量删除角色菜单(根据角色ID)"""
        self.session.exec(select(SystemRoleMenu).where(SystemRoleMenu.role_id == role_id)).delete()
        self.session.commit()

    async def batch_save_by_menu_ids(self, role_id: int, menu_ids: str):
        """批量写入角色菜单"""
        if menu_ids:
            perms = []
            # 假设 menu_ids 是一个逗号分隔的字符串，需要先转换为列表
            menu_ids_list = [int(menu_id) for menu_id in menu_ids.split(',')]

            # 准备要插入的数据
            new_perms = [
                SystemRoleMenu(role_id=role_id, menu_id=menu_id, create_time=int(time.time()), update_time=int(time.time()))
                for menu_id in menu_ids_list
            ]

            # 构建批量插入语句
            insert_stmt = insert(SystemRoleMenu).values([perm.dict() for perm in new_perms])

            # 执行插入语句
            self.session.execute(insert_stmt)
            self.session.commit()

            return new_perms

    async def batch_delete_by_menu_id(self, menu_id: int):
        """批量删除角色菜单(根据菜单ID)"""
        stmt = delete(SystemRoleMenu).where(SystemRoleMenu.menu_id == menu_id)
        self.session.execute(stmt)
        self.session.commit()